package com.cli.springboottemplateengine.engine;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.stereotype.Component;

import java.io.StringWriter;
import java.util.Map;

@Component
public class FreemarkerTemplateEngine implements TemplateEngine {

    private final Configuration configuration;

    public FreemarkerTemplateEngine() {
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setTemplateLoader(new StringTemplateLoader());
    }

    @Override
    public String doRender(String templateContent, Map<String, Object> model) {
        try {
            StringTemplateLoader loader = (StringTemplateLoader) configuration.getTemplateLoader();
            loader.putTemplate("inline", templateContent);
            Template template = configuration.getTemplate("inline");
            StringWriter writer = new StringWriter();
            template.process(model, writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("Freemarker 渲染失败", e);
        }
    }

    @Override
    public String getType() {
        return "freemarker";
    }
}
